import json
import sys
import time

from django.contrib import auth
from django.contrib.auth import logout, login, update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, FileResponse
from django.shortcuts import render, redirect
from EVA.models import *
from django.contrib import messages

# Create your views here.
# -----管理员-----
from EvaManageSys import settings


def admin_login(request):
    error_msg = ''
    # return HttpResponse("OK,Test!!!")
    if request.method == 'POST':
        user_id = request.POST.get('user')
        pwd = request.POST.get('pwd')
        user = auth.authenticate(request, username=user_id, password=pwd)
        if user is not None:
            if user.is_superuser == 1:
                login(request, user)
                return redirect('/admin_index/')
            else:
                error_msg = '非管理员用户，请前往普通用户登录页面'
        else:
            error_msg = '用户名或密码错误'
            # return redirect('/login/')
    return render(request, 'admin_login.html', {'error_msg': error_msg})


def admin_register(request):
    error_msg = ''
    if request.method == 'POST':
        user_name = request.POST.get('user_name')
        user_sex = request.POST.get('user_sex')
        user_birth = request.POST.get('user_birth')
        user_id = request.POST.get('card_id')
        user_phone = request.POST.get('user_phone')
        user_email = request.POST.get('user_email')
        user_birthplace = request.POST.get('user_birthplace')
        user_unit = request.POST.get('user_unit')
        user_photo = request.FILES.get('user_photo')
        user_pwd = request.POST.get('user_pwd')
        if user_id != '' and user_pwd != '':
            if user_photo is None:
                if user_sex == '男':
                    user_photo = 'user_photos/man.jpg'
                else:
                    user_photo = 'user_photos/woman.jpg'
            UserInfo.objects.create_superuser(user_name=user_name, user_sex=user_sex,
                                              user_birth=user_birth, username=user_id,
                                              user_phone=user_phone, user_email=user_email,
                                              user_birthplace=user_birthplace, user_unit=user_unit,
                                              user_photo=user_photo, password=user_pwd)
            return redirect('/admin_login/')
        else:
            error_msg = '身份证号码或密码不能为空'
    return render(request, 'admin_register.html', {'error_msg': error_msg})


@login_required
def admin_index(request):
    return render(request, 'index.html')


def admin_loginout(request):
    logout(request)
    return redirect('/admin_login/')


@login_required
def admin_userlist(request):
    users = UserInfo.objects.filter(is_superuser=0)
    return render(request, 'admin_user_list.html', {'users': users})


@login_required
def admin_adduser(request):
    user_name = request.POST.get('user_name')
    user_sex = request.POST.get('user_sex')
    user_birth = request.POST.get('user_birth')
    card_id = request.POST.get('card_id')
    user_phone = request.POST.get('user_phone')
    user_email = request.POST.get('user_email')
    user_birthplace = request.POST.get('user_birthplace')
    user_unit = request.POST.get('user_unit')
    user_photo = request.FILES.get('user_photo')
    user_pwd = request.POST.get('user_pwd')
    if user_photo is None:
        if user_sex == '男':
            user_photo = 'user_photos/man.jpg'
        else:
            user_photo = 'user_photos/woman.jpg'
    UserInfo.objects.create_user(user_name=user_name, user_sex=user_sex,
                                 user_birth=user_birth, username=card_id,
                                 user_phone=user_phone, user_email=user_email,
                                 user_birthplace=user_birthplace, user_unit=user_unit,
                                 user_photo=user_photo, password=user_pwd)
    return redirect('/admin_userlist/')


@login_required
def admin_deluser(request):
    # 1. 获取要删除的出版社id
    del_id = request.GET.get('id')
    # 2. 根据id去数据库删除
    # delete from press where id = del_id
    UserInfo.objects.filter(id=del_id).delete()
    # 3. 回到出版社列表
    return redirect('/admin_userlist/')


@login_required
def admin_edituser(request):
    edit_id = request.GET.get('id')

    user_name = request.POST.get('user_name')
    user_sex = request.POST.get('user_sex')
    user_birth = request.POST.get('user_birth')
    user_phone = request.POST.get('user_phone')
    user_email = request.POST.get('user_email')
    user_birthplace = request.POST.get('user_birthplace')
    user_unit = request.POST.get('user_unit')
    user_photo = request.FILES.get('user_photo')

    edit_user_now = UserInfo.objects.get(id=edit_id)

    edit_user_now.user_name = user_name
    edit_user_now.user_sex = user_sex
    edit_user_now.user_birth = user_birth
    edit_user_now.user_phone = user_phone
    edit_user_now.user_email = user_email
    edit_user_now.user_birthplace = user_birthplace
    edit_user_now.user_unit = user_unit
    if user_photo is None:
        pass
    else:
        edit_user_now.user_photo = user_photo

    edit_user_now.save()
    return redirect('/admin_userlist/')


@login_required
def admin_user_eva(request):
    users = UserInfo.objects.all()
    user_app = {}
    for user in users:
        user_app[user.id] = Appraising.objects.filter(user_id_id=user.id, app_status=1).count()
    print(user_app)
    return render(request, 'admin_user_eva.html', {'users': users, 'user_app': user_app})


@login_required
def admin_user_catEva(request):
    user_id = request.GET.get('id')
    user1 = UserInfo.objects.get(id=user_id)
    app_list = Appraising.objects.filter(user_id_id=user1.id, app_status=1)
    return render(request, 'admin_user_catEva.html', {'user1': user1, 'app_list': app_list})


@login_required
def admin_eva_app(request):
    app_list = Appraising.objects.filter(app_status=0)
    user_dict = {}
    for app in app_list:
        user = UserInfo.objects.get(id=app.user_id_id)
        dict1 = {'user_name': user.user_name, 'card_id': user.username}
        user_dict[app.id] = dict1
    return render(request, 'admin_eva_app.html', {'app_list': app_list, 'user_dict': user_dict})


@login_required
def admin_to_app(request):
    app_id = request.GET.get('id')
    statue = request.POST.get('app')
    app = Appraising.objects.get(id=app_id)
    app.app_status = statue
    app.save()
    messages.success(request, '提交成功！')
    return redirect('/admin_eva_app/')


@login_required
def admin_eva_apped(request):
    app_list = Appraising.objects.filter(app_status=1)
    user_dict = {}
    for app in app_list:
        user = UserInfo.objects.get(id=app.user_id_id)
        dict1 = {'user_name': user.user_name, 'card_id': user.username}
        user_dict[app.id] = dict1
    return render(request, 'admin_eva_apped.html', {'app_list': app_list, 'user_dict': user_dict})


@login_required
def admin_eva_unapp(request):
    app_list = Appraising.objects.filter(app_status=-1)
    user_dict = {}
    for app in app_list:
        user = UserInfo.objects.get(id=app.user_id_id)
        dict1 = {'user_name': user.user_name, 'card_id': user.username}
        user_dict[app.id] = dict1
    return render(request, 'admin_eva_unapp.html', {'app_list': app_list, 'user_dict': user_dict})


@login_required
def admin_eva_delapp(request):
    # 1. 获取要删除的出版社id
    del_id = request.GET.get('id')
    # 2. 根据id去数据库删除
    # delete from press where id = del_id
    Appraising.objects.filter(id=del_id).delete()
    # 3. 回到出版社列表
    messages.success(request, '成功删除信息!')
    return redirect('/admin_eva_unapp/')


import jinja2
from docxtpl import DocxTemplate
from docxtpl import InlineImage
from docx.shared import Mm
import os


@login_required
def admin_upload_word(request):
    user_id = request.GET.get('id')
    user1 = UserInfo.objects.get(id=user_id)
    app_list = Appraising.objects.filter(user_id_id=user1.id, app_status=1)
    apps = []
    for app in app_list:
        app_dict = {'app_name': app.app_name, 'app_data': app.app_data}
        apps.append(app_dict)
    tpl = DocxTemplate('static/template.docx')
    photo_url = sys.path[0] + r'/media/{}'.format(user1.user_photo)
    print(photo_url)
    context = {'user_name': user1.user_name,
               'user_sex': user1.user_sex,
               'username': user1.username,
               'user_birth': user1.user_birth,
               'user_phone': user1.user_phone,
               'user_email': user1.user_email,
               'user_birthplace': user1.user_birthplace,
               'user_unit': user1.user_unit,
               'user_photo': InlineImage(tpl, photo_url, width=Mm(40), height=Mm(56)),
               'app_list': apps
               }
    file_url = sys.path[0] + r'/media/datefile/{}.docx'.format(user1.username)
    jinja_env = jinja2.Environment(autoescape=True)
    tpl.render(context, jinja_env)
    tpl.save(file_url)
    time.sleep(2)
    file = open(file_url, 'rb')
    response = FileResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{}.docx"'.format(user1.username)
    return response
    # return redirect('/admin_user_catEva/?id={}'.format(user1.id))


import pandas as pd


@login_required
def admin_user_excel(request):
    f = request.FILES['user_file']
    filepath = os.path.join(settings.MEDIA_ROOT, f.name)
    data = pd.read_excel(f, sheet_name=0, dtype=str,
                         names=['username', 'user_name', 'user_sex', 'user_birth', 'user_phone', 'user_email',
                                'user_birthplace', 'user_unit', 'password'])

    for index, row in data.iterrows():
        if row['user_sex'] == '男':
            UserInfo.objects.create_user(username=row['username'], user_name=row['user_name'], user_sex=row['user_sex'],
                                         user_birth=row['user_birth'], user_phone=row['user_phone'],
                                         user_email=row['user_email'],
                                         user_birthplace=row['user_birthplace'], user_unit=row['user_unit'],
                                         password=row['password'], user_photo='user_photos/man.jpg')
        else:
            UserInfo.objects.create_user(username=row['username'], user_name=row['user_name'], user_sex=row['user_sex'],
                                         user_birth=row['user_birth'], user_phone=row['user_phone'],
                                         user_email=row['user_email'],
                                         user_birthplace=row['user_birthplace'], user_unit=row['user_unit'],
                                         password=row['password'], user_photo='user_photos/woman.jpg')
    messages.success(request, '添加成功！')
    return redirect('/admin_userlist/')

@login_required
def admin_update_excel(request):
    file_url = sys.path[0] + r'/static/userdemo.xls'
    print(file_url)
    file = open(file_url, 'rb')
    response = FileResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="demofile.xls"'
    return response
# --------------------------------------

def user_login(request):
    error_msg = ''
    # return HttpResponse("OK,Test!!!")
    if request.method == 'POST':
        user_id = request.POST.get('user')
        pwd = request.POST.get('pwd')
        user1 = auth.authenticate(request, username=user_id, password=pwd)
        if user1 is not None:
            login(request, user1)
            return redirect('/user_index/')
        else:
            error_msg = '用户名或密码错误'
            # return redirect('/login/')
    return render(request, 'user_login.html', {'error_msg': error_msg})


def user_register(request):
    error_msg = ''
    if request.method == 'POST':
        user_name = request.POST.get('user_name')
        user_sex = request.POST.get('user_sex')
        user_birth = request.POST.get('user_birth')
        user_id = request.POST.get('card_id')
        user_phone = request.POST.get('user_phone')
        user_email = request.POST.get('user_email')
        user_birthplace = request.POST.get('user_birthplace')
        user_unit = request.POST.get('user_unit')
        user_photo = request.FILES.get('user_photo')
        user_pwd = request.POST.get('user_pwd')
        if user_id != '' and user_pwd != '':
            if user_photo is None:
                if user_sex == '男':
                    user_photo = 'user_photos/man.jpg'
                else:
                    user_photo = 'user_photos/woman.jpg'
            UserInfo.objects.create_user(user_name=user_name, user_sex=user_sex,
                                         user_birth=user_birth, username=user_id,
                                         user_phone=user_phone, user_email=user_email,
                                         user_birthplace=user_birthplace, user_unit=user_unit,
                                         user_photo=user_photo, password=user_pwd)
            return redirect('/user_login/')
        else:
            error_msg = '身份证号码或密码不能为空'
    return render(request, 'user_register.html', {'error_msg': error_msg})


@login_required
def user_index(request):
    user = request.user
    app_list = Appraising.objects.filter(user_id_id=user.id, app_status=1)
    return render(request, 'user_index.html', {'app_list': app_list})


@login_required
def user_loginout(request):
    logout(request)
    return redirect('/user_login/')


@login_required
def user_edit(request):
    user = request.user
    if request.method == 'POST':
        user_name = request.POST.get('user_name')
        user_sex = request.POST.get('user_sex')
        user_birth = request.POST.get('user_birth')
        user_phone = request.POST.get('user_phone')
        user_email = request.POST.get('user_email')
        user_birthplace = request.POST.get('user_birthplace')
        user_unit = request.POST.get('user_unit')
        user_photo = request.FILES.get('user_photo')

        edit_user_now = UserInfo.objects.get(id=user.id)

        edit_user_now.user_name = user_name
        edit_user_now.user_sex = user_sex
        edit_user_now.user_birth = user_birth
        edit_user_now.user_phone = user_phone
        edit_user_now.user_email = user_email
        edit_user_now.user_birthplace = user_birthplace
        edit_user_now.user_unit = user_unit
        if user_photo == None:
            pass
        else:
            edit_user_now.user_photo = user_photo

        edit_user_now.save()
        messages.success(request, '成功修改信息!')
        return redirect('/user_edit')
    return render(request, 'user_edit.html')


@login_required
def user_edit_pwd(request):
    user = request.user
    pwd1 = request.POST.get('pwd1')
    pwd2 = request.POST.get('pwd2')
    if pwd1 == pwd2:
        user.set_password(pwd1)
        user.save()
        messages.success(request, '成功修改密码!')
        update_session_auth_hash(request, user)
    else:
        messages.error(request, '修改失败，两次密码输入不同!')
    return redirect('/user_edit/')


@login_required
def user_eva(request):
    user_id = request.user.id
    app_list = Appraising.objects.filter(user_id_id=user_id)
    app_list0, app_list1, app_list2 = list(), list(), list()
    for app in app_list:
        if app.app_status == 0:
            app_list0.append(app)
        elif app.app_status == 1:
            app_list1.append(app)
        elif app.app_status == -1:
            app_list2.append(app)
    return render(request, 'user_eva.html', {'app_list0': app_list0, 'app_list1': app_list1, 'app_list2': app_list2})


def eva_photo(request):
    app_id = request.GET.get('id')
    photos = Picture.objects.filter(app_id_id=app_id)
    picture_json = {}
    for photo1 in photos:
        picture_json[photo1.id] = photo1.photo.url
    return HttpResponse(json.dumps(picture_json), content_type='application/json')


@login_required
def eva_add(request):
    app_name = request.POST.get('app_name')
    app_data = request.POST.get('app_data')
    app_photos = request.FILES.getlist('app_photos')
    user_id = request.user.id
    app = Appraising.objects.create(app_name=app_name, app_data=app_data, app_status=0, user_id_id=user_id)

    for photo in app_photos:
        Picture.objects.create(app_id_id=app.id, photo=photo)
    return redirect('/user_eva/')


@login_required
def eva_del(request):
    del_id = request.GET.get('id')
    # 2. 根据id去数据库删除
    # delete from press where id = del_id
    Appraising.objects.filter(id=del_id).delete()
    # 3. 回到列表
    messages.success(request, '删除成功!')
    return redirect('/user_eva/')
